package cn.cttic.order.service.impl;

import cn.cttic.common.core.exception.order.OrderException;
import cn.cttic.common.core.utils.MapstructUtils;
import cn.cttic.common.core.utils.StringUtils;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.order.api.domain.BaseReconciliation;
import cn.cttic.order.mapper.BaseReconciliationMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.cttic.order.api.domain.bo.BaseReconciliationDetailBo;
import cn.cttic.order.api.domain.vo.BaseReconciliationDetailVo;
import cn.cttic.order.api.domain.BaseReconciliationDetail;
import cn.cttic.order.mapper.BaseReconciliationDetailMapper;
import cn.cttic.order.service.IBaseReconciliationDetailService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 账单详情Service业务层处理
 *
 * @author Times.Studio
 * @date 2025-01-02
 */
@RequiredArgsConstructor
@Service
public class BaseReconciliationDetailServiceImpl implements IBaseReconciliationDetailService {

    private final BaseReconciliationDetailMapper baseMapper;

    private final BaseReconciliationMapper baseReconciliationMapper;

    /**
     * 查询账单详情
     *
     * @param id 主键
     * @return 账单详情
     */
    @Override
    public BaseReconciliationDetailVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询账单详情列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 账单详情分页列表
     */
    @Override
    public TableDataInfo<BaseReconciliationDetailVo> queryPageList(BaseReconciliationDetailBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseReconciliationDetail> lqw = buildQueryWrapper(bo);
        Page<BaseReconciliationDetailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的账单详情列表
     *
     * @param bo 查询条件
     * @return 账单详情列表
     */
    @Override
    public List<BaseReconciliationDetailVo> queryList(BaseReconciliationDetailBo bo) {
        LambdaQueryWrapper<BaseReconciliationDetail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseReconciliationDetail> buildQueryWrapper(BaseReconciliationDetailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseReconciliationDetail> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getReconciliationId()), BaseReconciliationDetail::getReconciliationId, bo.getReconciliationId());
        lqw.like(StringUtils.isNotBlank(bo.getCarOwnerName()), BaseReconciliationDetail::getCarOwnerName, bo.getCarOwnerName());
        lqw.eq(StringUtils.isNotBlank(bo.getCarNo()), BaseReconciliationDetail::getCarNo, bo.getCarNo());
        lqw.eq(StringUtils.isNotBlank(bo.getTerminalNameModel()), BaseReconciliationDetail::getTerminalNameModel, bo.getTerminalNameModel());
        lqw.eq(StringUtils.isNotBlank(bo.getTerminalImei()), BaseReconciliationDetail::getTerminalImei, bo.getTerminalImei());
        lqw.eq(StringUtils.isNotBlank(bo.getTerminalIccid()), BaseReconciliationDetail::getTerminalIccid, bo.getTerminalIccid());
        lqw.eq(bo.getInstallTime() != null, BaseReconciliationDetail::getInstallTime, bo.getInstallTime());
        lqw.eq(bo.getActiveTime() != null, BaseReconciliationDetail::getActiveTime, bo.getActiveTime());
        lqw.eq(bo.getLastOnlineTime() != null, BaseReconciliationDetail::getLastOnlineTime, bo.getLastOnlineTime());
        lqw.eq(bo.getOfflineDays() != null, BaseReconciliationDetail::getOfflineDays, bo.getOfflineDays());
        lqw.eq(StringUtils.isNotBlank(bo.getVehicleType()), BaseReconciliationDetail::getVehicleType, bo.getVehicleType());
        lqw.eq(bo.getVerifyStatus() != null, BaseReconciliationDetail::getVerifyStatus, bo.getVerifyStatus());
        lqw.eq(bo.getReviewStatus() != null, BaseReconciliationDetail::getReviewStatus, bo.getReviewStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getReviewReason()), BaseReconciliationDetail::getReviewReason, bo.getReviewReason());
        lqw.eq(StringUtils.isNotBlank(bo.getInstallOrderId()), BaseReconciliationDetail::getInstallOrderId, bo.getInstallOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getSaleOrderId()), BaseReconciliationDetail::getSaleOrderId, bo.getSaleOrderId());
        lqw.eq(bo.getCreateTime() != null, BaseReconciliationDetail::getCreateTime, bo.getCreateTime());
        return lqw;
    }

    /**
     * 新增账单详情
     *
     * @param bo 账单详情
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseReconciliationDetailBo bo) {
        BaseReconciliationDetail add = MapstructUtils.convert(bo, BaseReconciliationDetail.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改账单详情
     *
     * @param bo 账单详情
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseReconciliationDetailBo bo) {
        BaseReconciliationDetail update = MapstructUtils.convert(bo, BaseReconciliationDetail.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseReconciliationDetail entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除账单详情信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
//        if(isValid){
//
//        }
        for (String id : ids) {
            BaseReconciliationDetail detail = baseMapper.selectById(id);
            if (detail != null) {
                BaseReconciliation reconciliation = baseReconciliationMapper.selectById(detail.getReconciliationId());
                if (reconciliation.getOrderCount() <= 1) {
                    throw new OrderException("至少保留一条记录");
                }
                LambdaUpdateWrapper updateWrapper = Wrappers.lambdaUpdate(BaseReconciliation.class)
                        .eq(BaseReconciliation::getId, detail.getReconciliationId())
                        .set(BaseReconciliation::getOrderCount, reconciliation.getOrderCount() - 1);
            }
        }

        return baseMapper.deleteByIds(ids) > 0;
    }
}
